﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Codeplex.Data;
using System.Xml.Linq;


namespace nanobot {
    public class C_CEXcom {
        Form1 main_form;

        public string API_KEY { get; set; }
        public string MERCHANT_KEY { get; set; }
        public static string API_KEY_registry_key = "c_cexcom_API_KEY";
        public static string MERCHANT_KEY_registry_key = "c_cexcom_MERCHAND_KEY";

        string pairs_raw;
        string rate_ticker_raw;
        string trade_history_raw;
        string trade_volume_raw;
        string last_trade_volume_raw;
        string balance_raw;
        string make_order_raw;

        string [] pairs;
        string [] rate_ticker;
        string [] trade_history;
        string [] trade_volume;
        string [] last_trade_volume;
        string [] balance;
        string [] temp;

        public C_CEXcom (Form1 form) {
            API_KEY = ModifyRegistry.Read( API_KEY_registry_key );            
            if (string.IsNullOrEmpty(API_KEY)){
                ModifyRegistry.Write(API_KEY_registry_key, "48295E89956B8CC0D6CF1F28E3C60F01");
            }
            MERCHANT_KEY = ModifyRegistry.Read( MERCHANT_KEY_registry_key );
            if (string.IsNullOrEmpty(MERCHANT_KEY))
            {
                ModifyRegistry.Write(MERCHANT_KEY_registry_key, "48295E89956B8CC0D6CF1F28E3C60F01");
            }

            main_form = form;
        }

        public string[] GetPairs () {
            dynamic json;
            using ( var client = new WebClient() ) {
                // c-cex.com
                // pairs
                pairs_raw = client.DownloadString( "https://c-cex.com/t/pairs.json" );
                json = DynamicJson.Parse( pairs_raw );

                pairs_raw = pairs_raw.Replace( '\"', ' ' );
                temp = pairs_raw.Split( new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries );
                pairs = temp[1].Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
            }
            return pairs;

        }

        public string UpdateRateTicker ( string selected_pair ) {
            using ( var client = new WebClient() ) {
                rate_ticker_raw = client.DownloadString( "https://c-cex.com/t/prices.json" );
                rate_ticker_raw = rate_ticker_raw.Replace( '\"', ' ' );
                rate_ticker_raw = rate_ticker_raw.Remove( 0, 1 );
                rate_ticker_raw = rate_ticker_raw.Remove( rate_ticker_raw.Length - 2 );
                rate_ticker = rate_ticker_raw.Split( new string[] { ":{", "}," }, StringSplitOptions.RemoveEmptyEntries );

            }

            if ( selected_pair != string.Empty ) {
                int index = rate_ticker.ToList().IndexOf( selected_pair );
                index++;                
                string [] element_rate_ticker = rate_ticker[index].Split( new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries );

                if (element_rate_ticker.Length == 1) {
                    return string.Empty;
                }
                string temp = string.Empty;

                for ( int i = 0; i < element_rate_ticker.Length - 2; i += 2 ) {
                    temp += element_rate_ticker[i]
                        + "\t" + element_rate_ticker[i + 1] + Environment.NewLine;
                }
                temp += element_rate_ticker[element_rate_ticker.Length - 1] + "\t";
                temp += HelperClass.FromUnixTime( long.Parse( element_rate_ticker[element_rate_ticker.Length - 1] ) ).ToString();

                return temp;
            }
            return string.Empty;

        }

        public List<string[]> UpdateTradeHistory ( string selected_pair, string date_from, string date_to ) {
            using ( var client = new WebClient() ) {
                trade_history_raw = client.DownloadString( String.Format(
                        "https://c-cex.com/t/s.html?a=tradehistory&d1={0}&d2={1}&pair={2}",
                        date_from, date_to, selected_pair.Substring( 1, selected_pair.Length - 2 ) )
                        );

                //dynamic json = DynamicJson.Parse( trade_history_raw );

                List<string[]> result = new List<string[]>();

                if ( trade_history_raw != "{\"return\":\"No trade history for this period\"}\n" 
                    && trade_history_raw != "" 
                    && trade_history_raw != "{ return : No trade history for this period }\n" ) {
                    trade_history_raw = trade_history_raw.Replace( '\"', ' ' );
                    temp = trade_history_raw.Split( new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries );
                    temp[1] = temp[1].Remove( temp[1].Length - 1 );
                    trade_history = temp[1].Split( new string[] { "{", "}," }, StringSplitOptions.RemoveEmptyEntries );

                    string [] element_trade_history;

                    for ( int i = 0; i < trade_history.Length; i++ ) {
                        element_trade_history = trade_history[i].Split( new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries );
                        for ( int j = 0; j < element_trade_history.Length; j++ ) {
                            result.Add( new string[] {
                            element_trade_history[1] + ":"
                            + element_trade_history[2] + ":"
                            + element_trade_history[3],
                            element_trade_history[5],
                            element_trade_history[7],
                            element_trade_history[9],
                            element_trade_history[11]
                            } );

                        }
                    }
                    return result;

                    //string s_temp = string.Empty;
                    //if ( selected_pair != string.Empty ) {

                    //    s_temp = " Date & Time\t\tType\tAmount\t\tRate\t\tBackrate" + Environment.NewLine;
                    //    string [] c_cexcom_element_trade_history;
                    //    for ( int i = 0; i < trade_history.Length; i++ ) {
                    //        c_cexcom_element_trade_history = trade_history[i].Split( new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries );
                    //        s_temp += c_cexcom_element_trade_history[1] + ":"
                    //            + c_cexcom_element_trade_history[2] + ":"
                    //            + c_cexcom_element_trade_history[3] + "\t";     // datetime
                    //        s_temp += c_cexcom_element_trade_history[5] + "\t";   //type

                    //        s_temp += c_cexcom_element_trade_history[7].Length < 10 ?
                    //            c_cexcom_element_trade_history[7].PadRight( 10, '0' )
                    //            + "\t" : c_cexcom_element_trade_history[7] + "\t";    //amount



                    //        s_temp += c_cexcom_element_trade_history[9]
                    //            + ( c_cexcom_element_trade_history[9].Length > 8 ? "\t" : "\t\t" );   //rate
                    //        s_temp += c_cexcom_element_trade_history[11];  //backrate

                    //        s_temp += Environment.NewLine;

                    //    }

                    //}

                    //return s_temp;


                } else {
                    result.Add( new string[] { "No trade history for" + selected_pair + "for this period"} );
                    return result;

                }




            }
        }

        public List<string[]> UpdateTradeVolume ( string selected_pair, int hours ) {
            using ( var client = new WebClient() ) {
                trade_volume_raw = client.DownloadString( String.Format(
                        "https://c-cex.com/t/s.html?a=volume&h={0}&pair={1}",
                        hours, selected_pair.Substring( 1, selected_pair.Length - 2 ) )
                        );

                //dynamic json = DynamicJson.Parse( trade_history_raw );

                trade_volume_raw = trade_volume_raw.Replace( '\"', ' ' );
                temp = trade_volume_raw.Split( new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries );

                if (temp.Length != 0)
                {
                    temp[1] = temp[1].Remove(temp[1].Length - 1);
                    trade_volume = temp[1].Split(new string[] { "{", "}," }, StringSplitOptions.RemoveEmptyEntries);
                }

            }

            string [] pair = selected_pair.Split( new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries );
            List<string[]> result = new List<string[]>();

            for ( int i = 0; i < trade_volume.Length; i++ ) {
                string [] element_trade_volume = trade_volume[i].Split( new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries );

                result.Add( new string[] {
                            element_trade_volume[1] + ":"
                            + element_trade_volume[2] + ":"
                            + element_trade_volume[3],      // datetime from
                            element_trade_volume[5] + ":"
                            +element_trade_volume[6] + ":"
                            +element_trade_volume[7],       // datetime to
                            element_trade_volume[9],        // volume pair 1
                            element_trade_volume[11]        // volume pair 2
                            } );
            }
            //string s_temp = " From\t\t\t To\t\t\tVolume " + pair[0] + "\tVolume " + pair[1] + Environment.NewLine;

            //for ( int i = 0; i < trade_volume.Length; i++ ) {
            //    string [] c_cexcom_element_trade_volume
            //        = trade_volume[i].Split( new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries );


            //    s_temp += c_cexcom_element_trade_volume[1] + ":"
            //        + c_cexcom_element_trade_volume[2] + ":"
            //        + c_cexcom_element_trade_volume[3] + "\t";      // from

            //    s_temp += c_cexcom_element_trade_volume[5] + ":"
            //        + c_cexcom_element_trade_volume[6] + ":"
            //        + c_cexcom_element_trade_volume[7] + "\t";      // to

            //    s_temp += c_cexcom_element_trade_volume[9] +
            //        ( c_cexcom_element_trade_volume[9].Length > 8 ? "\t" : "\t\t" );
            //    //( c_cexcom_element_trade_volume[9].Length > 4 ) ? "\t\t" : "\t\t\t" );  // volume pair 1
            //    s_temp += c_cexcom_element_trade_volume[11]; // volume pair 2

            //    s_temp += Environment.NewLine;

            //}

            return result;

        }

        public List<string[]> UpdateLastTradeVolume ( string selected_pair, int hours ) {
            using ( var client = new WebClient() ) {
                last_trade_volume_raw = client.DownloadString( String.Format(
                        "https://c-cex.com/t/s.html?a=lastvolumes&h={0}",
                        hours ) );

                //dynamic json = DynamicJson.Parse( last_trade_volume_raw );

                last_trade_volume_raw = last_trade_volume_raw.Replace( '\"', ' ' );
                temp = last_trade_volume_raw.Split( new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries );
                temp[1] = temp[1].Remove( temp[1].Length - 1 );
                last_trade_volume = temp[1].Split( new string[] { "{", "}," }, StringSplitOptions.RemoveEmptyEntries );

            }

            string [] pair = selected_pair.Split( new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries );
            string s_temp = " Pair\t\tVolume " + pair[0] + "\t\tVolume " + pair[1] + Environment.NewLine;
            string [] element_last_trade_volume;
            List<string[]> result = new List<string[]>();


            for ( int i = 0; i < last_trade_volume.Length; i++ ) {
                element_last_trade_volume = last_trade_volume[i]
                    .Split( new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries );
                result.Add( new string[] { 
                    element_last_trade_volume[1].ToUpper(),
                    element_last_trade_volume[3],
                    element_last_trade_volume[5]
                });
               

            }

            return result;
        }

        public List<string[]> GetBalance () {
            List<string[]> result = new List<string[]>();
            //DynamicJson json;
            using ( var client = new WebClient() ) {
                balance_raw = client.DownloadString( String.Format(
                    "https://c-cex.com/t/r.html?key={0}&a=getbalance", API_KEY
                    ) );

                //json = DynamicJson.Parse( balance_raw );
                //var doc = XDocument.Load( balance_raw );
                //var key = doc.Elements( "return" );
                //var key2 = key.Single();
                //var key3 = key2.Value;
                balance_raw = balance_raw.Replace( '\"', ' ' );
                temp = balance_raw.Split( new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries );
                temp[1] = temp[1].Remove( temp[1].Length - 1 );
                balance = temp[1].Split( new string[] { "{", "}," }, StringSplitOptions.RemoveEmptyEntries );

            }
            string [] element_balance;
            for ( int i = 0; i < balance.Length; i++ ) {
                element_balance = balance[i].Split( new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries );

                result.Add( element_balance );
            }

            return result;

        }


        /// <summary>
        /// Not Done
        /// </summary>
        /// <param name="selectedPair"></param>
        /// <param name="amount"></param>
        /// <param name="rate"></param>
        /// <returns></returns>
        public string MakeOrder ( string selectedPair, double amount, char type, double rate ) {

            using ( var client = new WebClient() ) {
                make_order_raw = client.DownloadString( String.Format(
                    "https://c-cex.com/t/r.html?key={0}&a=makeorder&pair={1}&q={2}&t={3}&r={4}",
                    API_KEY, selectedPair, amount, type, rate
                    ));
                return make_order_raw;
            }

            //if ( make_order_raw == "Empty error" ) {
            //    return make_order_raw;
            //
            //}
            //dynamic order = DynamicJson.Parse( make_order_raw );

            //make_order_raw = make_order_raw.Replace( '\"', ' ' );
            //make_order_raw = make_order_raw.Remove( 0, 1 );
            //make_order_raw = make_order_raw.Remove( make_order_raw.Length - 1 );
            //
            //return make_order_raw.Split( new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries )[1];


        }

        public string CancelOrder ( int order_id ) {
            using ( var client = new WebClient() ) {
                string cancel_order_raw = client.DownloadString( 
                    String.Format( "https://c-cex.com/t/r.html?key={0}&a=cancelorder&id={1}", API_KEY, order_id )
                    );
                return cancel_order_raw;
                //return DynamicJson.Parse( cancel_order_raw );

            }

        }

        public string SelfTradeHistory ( string date_from, string date_to, string seleced_pair ) {
            List<string[]> result = new List<string[]>();
            using ( var client = new WebClient() ) {
                string self_trade_history_raw = client.DownloadString(
                    String.Format( "https://c-cex.com/t/r.html?key={0}&a=tradehistory&d1={1}&d2={2}&pair={3}"
                    , API_KEY, date_from, date_to, seleced_pair
                    )
                    );

                //dynamic json = DynamicJson.Parse( self_trade_history_raw );
                return self_trade_history_raw;
            }

            //return result;

        }

        public string GetOrderList (int self, string selected_pair ) {
            string order_list_raw = string.Empty;

            using ( var client = new WebClient() ) {
                order_list_raw = client.DownloadString( 
                    String.Format( 
                    "https://c-cex.com/t/r.html?key={0}&a=orderlist&self={1}&pair={2}"
                    , API_KEY, self, selected_pair
                    ) 
                );

                return order_list_raw;
            }
        }

        public static string[] get_id_order_list ( string str, int[] indecies ) {
            List<string> ids = new List<string>();
            int num;
            int  index1, index2;
            bool found;

            for ( int i = 0; i < indecies.Length; i++ ) {
                index1 = index2 = num = 0;
                found = false;

                for ( int j = indecies[i] - 1; j >= ( i == 0 ? 0 : indecies[i - 1] ); j-- ) {
                    if ( str[j] == '\"' ) {
                        num++;
                    }

                    if ( num == 1 && !found ) {
                        index1 = j;
                        found = true;
                    }

                    if ( num == 2 ) {
                        index2 = j + 1;
                        break;
                    }

                }

                ids.Add( str.Substring( index2, index1 - index2 ) );

            }



            return ids.ToArray();

        }




    }
}
